import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:native_dart_package/http/request/exception/exception_handler.dart';
import 'package:native_dart_package/loading/loading_util.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/configs.dart';
import 'package:yt_devops/pages/site/site_setting/siet_elec_price_setting/site_elec_price_setting_model.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/services/device/device_sevices.dart';
import 'package:yt_devops/services/site/site_services.dart';
import 'package:yt_devops/utils/enums.dart';

class SietMainsElecDetailController extends GetxController
    with GetTickerProviderStateMixin {
  late int id;
  SiteElecPriceSettingModel model = SiteElecPriceSettingModel();
  bool isEnableEdit = false;

  String monetaryUnitName = '元';
  /// 站点列表服务
  SiteServices siteServices = Get.put(SiteServices());
  RefreshController refreshController = RefreshController(
    initialRefresh: false,
  );

  bool isEnableCommit = false;
  late int siteId;
  List<String> titleStringList = [
    ResKey.basicInfo.tr,
    ResKey.basicEleFee.tr,
    ResKey.peakValleyElePrices.tr,
    ResKey.siteSettingEffectiveDate.tr,
    ResKey.siteSettingElectricityStagePrice.tr
  ];
  List<String> titleDetailList = [
    ResKey.siteSettingElectricityRoleName.tr,
    ResKey.siteSettingElectricityPowerFactor.tr,
    ResKey.siteSettingElectricityMaxNeed.tr,
    ResKey.siteSettingElectricityNeedCapacityBill.tr,
    ResKey.siteSettingElectricityShapePrice.tr,
    ResKey.siteSettingElectricityPeakPrice.tr,
    ResKey.siteSettingElectricityAveragePrice.tr,
    ResKey.siteSettingElectricityValleyPrice.tr
  ];
  List<String> unitList = [
    '',
    '',
    'kW',
    ResKey.yuan.tr,
    '${ResKey.yuan.tr}/kWh',
    '${ResKey.yuan.tr}/kWh',
    '${ResKey.yuan.tr}/kWh',
    '${ResKey.yuan.tr}/kWh'
  ];
  List<dynamic> timeDateList = [
    {
      'effectiveTime': '01-01',
      'expirationTime': '12-31',
    }
  ];
  List<dynamic> peakAndPlateauList = [
    {'intervalStartTime': '00:00', 'intervalEndTime': '24:00', 'type': 0}
  ];
  int status = 1;
  int electricityType = 0;
  final DeviceServices services = Get.put(DeviceServices());
  final TextEditingController ruleNameController = TextEditingController();
  final TextEditingController powerElementController = TextEditingController();
  final TextEditingController maxCapacityController = TextEditingController();
  final TextEditingController needPriceController = TextEditingController();

  final TextEditingController maxPriceController = TextEditingController();
  final TextEditingController peakPriceController = TextEditingController();
  final TextEditingController averageProtectController =
      TextEditingController();
  final TextEditingController valleyReleaseController = TextEditingController();
  @override
  void onInit() {
    super.onInit();
    if (Get.arguments != null) {
      id = Get.arguments['id'];
      siteId = Get.arguments['siteId'];
    }
    GetStorage storage = GetStorage();
    monetaryUnitName = storage.read('monetaryUnitName')??'元';
    if(monetaryUnitName == '元' || monetaryUnitName == '¥'){
      monetaryUnitName = ResKey.yuan.tr;
    }
    unitList = [
      '',
      '',
      'kW',
      monetaryUnitName,
      '$monetaryUnitName/kWh',
      '$monetaryUnitName/kWh',
      '$monetaryUnitName/kWh',
      '$monetaryUnitName/kWh'
    ];
    if (refreshController.isRefresh) {
      refreshController.refreshCompleted();
    }
    loadData(refereshType: RefereshType.load);
  }

  void edit() {
    isEnableEdit = true;
    update();
  }

  /// 请求站点-市电电价详情数据
  Future<void> loadData(
      {RefereshType refereshType = RefereshType.refresh}) async {
    Configs.httpClient.requestWithLoading(
      () async {
        var params = {'id': id};
        var data = await siteServices.getSiteMainsDetail(params);
        var temp = SiteElecPriceSettingModel.fromJson(data);
        model = temp;
        ruleNameController.text = model.name != null ? model.name! : '';
        powerElementController.text =
            model.powerFactor != null ? model.powerFactor! : '';
        maxCapacityController.text =
            model.maxDemand != null ? model.maxDemand! : '';
        needPriceController.text = model.demandElectrovalency != null
            ? model.demandElectrovalency!
            : '';
        maxPriceController.text =
            model.sharpPrice != null ? model.sharpPrice! : '';
        peakPriceController.text =
            model.peakPrice != null ? model.peakPrice! : '';
        averageProtectController.text =
            model.flatPrice != null ? model.flatPrice! : '';
        valleyReleaseController.text =
            model.valleyPrice != null ? model.valleyPrice! : '';
        status = model.status != null ? model.status! : 0;
        electricityType =
            model.electricityType != null ? model.electricityType! : 0;

        checkCommitStatus();
        if (model.effectiveTimeList != null) {
          timeDateList.clear();
          for (var element in model.effectiveTimeList!) {
            timeDateList.add({
              "effectiveTime": element.effectiveTime,
              "expirationTime": element.expirationTime,
            });
          }
        }
        if (model.hoursPriceList != null) {
          peakAndPlateauList.clear();
          for (var element in model.hoursPriceList!) {
            peakAndPlateauList.add({
              "intervalStartTime": element.intervalStartTime,
              "intervalEndTime": element.intervalEndTime,
              "type": element.type
            });
          }
        }
        update();
      },
      onError: (error) {
        refreshController.loadFailed();
        showError(error.message);
        return true;
      },
    );
  }

  Future<void> save() async {
    var param = {
      "name": ruleNameController.text,
      "status": status,
      "siteId": siteId,
      'id': id,
      // "powerFactor": powerElementController.text,
      "electricityType": electricityType,
      // "maxDemand": maxCapacityController.text,
      // "demandElectrovalency": needPriceController.text,
    };
    if (timeDateList.isNotEmpty) {
      param['effectiveTimeList'] = timeDateList;
    }


    if (peakAndPlateauList.isNotEmpty) {
      param['hoursPriceList'] = peakAndPlateauList;
    }
    if (powerElementController.text.isNotEmpty) {
      param['powerFactor'] = powerElementController.text;
    }
    if (maxCapacityController.text.isNotEmpty) {
      param['maxDemand'] = maxCapacityController.text;
    }
    if (needPriceController.text.isNotEmpty) {
      param['demandElectrovalency'] = needPriceController.text;
    }


    if (maxPriceController.text.isNotEmpty) {
      param['sharpPrice'] = maxPriceController.text;
    }
    if (valleyReleaseController.text.isNotEmpty) {
      param['valleyPrice'] = valleyReleaseController.text;
    }
    if (averageProtectController.text.isNotEmpty) {
      param['flatPrice'] = averageProtectController.text;
    }
    if (peakPriceController.text.isNotEmpty) {
      param['peakPrice'] = peakPriceController.text;
    }

    showLoading(toast: ResKey.loading.tr);
    var result = await services.siteMainsUpdate(
      param,
      onError: (p0) {
        dismissLoading();
        handleException(p0);

        return false;
      },
    );
    dismissLoading();
    Log.d('result==' + result.toString());
    if (result == true) {
      Get.back(result: true);
    }
  }

  ///下一步按钮是否可以点击
  checkCommitStatus() {
    if (ruleNameController.text.isNotEmpty && timeDateList.isNotEmpty && peakAndPlateauList.isNotEmpty){
      isEnableCommit = true;
    } else {
      isEnableCommit = false;
    }
    Log.d('isEnableCommit==' + isEnableCommit.toString());
    update();
  }


  void cancelEdit() {
    isEnableEdit = false;
    update();
  }


  void updateTimeList() {
    timeDateList.addAll([
      {
        'effectiveTime': '01-01',
        'expirationTime': '12-31',
      }
    ]);
    checkCommitStatus();
    update();
  }

  void deleteTimeList(int index) {
    timeDateList.removeAt(index);
    checkCommitStatus();
    update();
  }

  void updatePeakAndPlateauListList() {
    peakAndPlateauList.addAll([
      {"intervalStartTime": "00:00", "intervalEndTime": "24:00", 'type': 0}
    ]);
    checkCommitStatus();
    update();
  }

  void deletePeakAndPlateauListList(int index) {
    peakAndPlateauList.removeAt(index);
    checkCommitStatus();
    update();
  }

  String handleTimeToHour(DateTime? time) {
    Log.d('DateTime==' + time.toString());
    if (time != null) {
      String str = time.toString();
      if (time.toString().length > 16) {
        String timeString = '${str.substring(11, 13)}:${str.substring(14, 16)}';
        if (timeString == '24:00') {
          timeString = '24:00';
        }
        Log.d('timeString==' + timeString.toString());
        return timeString;
      }
    }

    return '';
  }

  String handleTimeToMonth(DateTime? time) {
    Log.d('DateTime==' + time.toString());
    if (time != null) {
      String str = time.toString();
      if (time.toString().length > 16) {
        return '${str.substring(5, 7)}-${str.substring(8, 10)}';
      }
    }

    return '';
  }

  ///初始化开始时间从零点开始
  DateTime initStartTime() {
    var now = DateTime.now(); //当前时间
    DateTime date = DateTime(now.year, now.month, now.day, 00, 00);
    Log.d('date2==' + date.toString());
    return date;
  }

  ///初始化开始时间23:59结束
  DateTime initEndTime() {
    var now = DateTime.now(); //当前时间
    DateTime date = DateTime(now.year, now.month, now.day, 23, 59);
    Log.d('date2==' + date.toString());
    return date;
  }
}
